<template>
    <div class="big_box">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>项目管理</el-breadcrumb-item>
            <el-breadcrumb-item>项目列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-divider></el-divider>

        <el-form :model="selectfrom" ref="_selectfrom">
            <el-row :gutter="20">
                <el-col :span="2">
                    <el-select placeholder="请选择负责人" v-model="selectfrom.project.HeadUserId" filterable>
                        <el-option value="" label="请选择负责人"></el-option>
                        <el-option v-for="item in $store.state.AllUsers" :value="item.Id"
                            :label="item.UserName"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-select placeholder="请选择项目" v-model="selectfrom.project.Id" filterable>
                        <el-option :value="0" label="请选择项目"></el-option>
                        <el-option v-for="item in AllProject" :value="item.Id" :label="item.ProjectName"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2">
                    <el-date-picker style="width: 100%" placeholder="开始日期" type="date" value-format="yyyy-MM-dd"
                        v-model="selectfrom.StartDate"></el-date-picker>
                </el-col>
                <el-col :span="2">
                    <el-date-picker style="width: 100%" placeholder="结束日期" type="date" value-format="yyyy-MM-dd"
                        v-model="selectfrom.EndDate"></el-date-picker>
                </el-col>
                <el-col :span="1">
                    <el-button icon="el-icon-search" @click="formdata"></el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-row style="padding:10px 0px">
            <el-col>
                <el-button-group >
                    <el-button class="buttongroup" type="danger" icon="el-icon-delete" @click="BatchDelete_event" v-show="$store.state.user.roleid == 1">批量删除
                    </el-button>
                    <el-button class="buttongroup" type="success" icon="el-icon-circle-plus-outline"  v-show="$store.state.user.roleid == 1"
                        @click="createNewProjectEvent()">新建项目
                    </el-button>
					<el-button class="buttongroup" type="info" icon="el-icon-bank-card" @click="PayrollFormNew_Entry.show = true">生活费计划</el-button>
                </el-button-group>	
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-table :data="tableData" border show-summary :summary-method="getSummaries" @select="tableSelectEvent"
				@select-all="tableSelectEvent" stripe style="width: 100%" @selection-change="SelectionChange_event">
                    <el-table-column type="selection" width="40" align="center"></el-table-column>
                    <el-table-column fixed type="index" label="序号" width="50" align="center"
                        :index="indexMethod"></el-table-column>
                    <el-table-column fixed prop="ProjectNumber" label="项目编号" align="center"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column fixed prop="ProjectName" label="项目名称" align="center"
                        show-overflow-tooltip></el-table-column>
                    <el-table-column prop="HeadUserId" label="负责人" show-overflow-tooltip align="center">
                        <template slot-scope="slot">
                            {{ GetUserName(slot.row.HeadUserId) }}
                        </template>
                    </el-table-column>

                    <el-table-column fixed prop="ProjectAddress" label="工程地址" align="center"
                        show-overflow-tooltip></el-table-column>

                    <el-table-column fixed prop="ConstructionUnit" label="施工单位" align="center"
                        show-overflow-tooltip></el-table-column>

                    <el-table-column prop="EstimatedContractAmount" label="合同总价" align="center" show-overflow-tooltipalign="center"></el-table-column>
                    <el-table-column fixed prop="Managementfee" label="管理费" align="center"
                        show-overflow-tooltip></el-table-column>

                    <el-table-column prop="StartDate" label="开始日期" show-overflow-tooltip align="center">
						<template slot-scope="scope">
							{{ shijianzhuanhua(scope.row.StartDate) }}
						</template>
					</el-table-column>
                    <el-table-column prop="EndDate" label="结束日期" show-overflow-tooltip align="center">
						<template slot-scope="scope">
							{{ shijianzhuanhua(scope.row.EndDate) }}
						</template>
					</el-table-column>
					<el-table-column prop="EndDate" label="项目状态" show-overflow-tooltip align="center">
						<template slot-scope="scope">
							<p style="color: #409EFF;" v-if="scope.row.ProjectStatus == 0">进行中</p>
							<p style="color: #67C23A;" v-else>已完结</p>
						</template> 
					</el-table-column>

                    <el-table-column prop="address" header-align="center" align="center" label="操作" fixed="right" width="400px">
                        <template slot-scope="scope">
                            <el-button type="primary" class="BtnSize" size="mini" plain 
                                @click="RetrievApply_event(scope.row)"> 报销单
                            </el-button>
                            <el-button type="primary" class="BtnSize" size="mini" plain 
                                @click="RetrievPayRoll_event(scope.row)"> 收方工资单
                            </el-button>
   <!--                         <el-button type="success" class="BtnSize" size="mini" plain 
                                @click="RetrievPayRollReality_event(scope.row)"> 实际发放工资单
                            </el-button> -->
							<el-button type="primary" class="BtnSize" size="mini" plain 
							    @click="PersonnelEntry_event(scope.row)"> 人员录入
							</el-button>
                            <div v-if="ProjectDe" style="padding-top: 10px;">
                                <el-popconfirm style="margin-right: 10px;"
							  confirm-button-text='确定'
							  cancel-button-text='取消'
							  icon="el-icon-info"
							  icon-color="red"
							  @confirm="projectOver_Event(scope.row)"
							  title="你确定要完成此项目吗？">
								<el-button slot="reference" type="success"  size="mini" plain v-show="scope.row.ProjectStatus!=1">项目完结</el-button>							
							</el-popconfirm>
                                <el-button type="info" class="BtnSize" size="mini" plain 
                                    @click="TableProjectEvent(scope.row, 'Approval')">编辑
                                </el-button>
                                <el-button type="danger" class="BtnSize" size="mini" plain 
                                    @click="BatchDeleteOne_event(scope.row)"> 删除
                                </el-button>
                            </div>

                        </template>
                    </el-table-column>
                    <!-- <el-table-column fixed="right" label="操作"  align="center">
                        <template slot="header" slot-scope="scope">
                            操作
                            <el-tooltip placement="top">
                                <el-button v-show="buttonShow" type="success" size="mini" plain
                                       @click="TableProjectEvent(scope.row,'Approval')">编辑
                            </el-button>
                            <el-button v-show="buttonShow" type="danger" size="mini" plain
                                       @click="BatchDeleteOne_event(scope.row)">删除
                            </el-button>
                            </el-tooltip>
                        </template>
                        <template slot-scope="scope">
                            <el-button v-show="buttonShow" type="success" size="mini" plain
                                       @click="TableProjectEvent(scope.row,'Approval')">编辑
                            </el-button>
                            <el-button v-show="buttonShow" type="danger" size="mini" plain
                                       @click="BatchDeleteOne_event(scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
            </el-col>
            <el-col :span="24">
                <div class="block">
                    <el-pagination @size-change="formdata" @current-change="formdata"
                        :current-page.sync="pagination.currentPage" :page-sizes="pagination.pagesizes"
                        :page-size.sync="pagination.pagesize" layout="total, sizes, prev, pager, next, jumper"
                        :total.sync="pagination.total">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>

        <el-dialog :visible.sync="Project_filing_dialog" width="90%" top="10px" title="项目备案">
            <ProjectFiling :UpProject="UpProject" :filetype="add"></ProjectFiling>
        </el-dialog>

        <el-dialog :visible.sync="Approval_dialog.show" width="90%" top="10px" title="项目备案">
            <Approval :all-department="AllDepartment" :project-data="Approval_dialog.projectdata"></Approval>
        </el-dialog>


        <el-dialog :visible.sync="ProjectFinance_dialog.show" width="80%" top="10px" title="项目财务--公司公用">
            <ProjectFinance :project="ProjectFinance_dialog.project">

            </ProjectFinance>
        </el-dialog>

        <el-dialog :visible.sync="ProjectSummary_dialog.show" width="80%" top="10px" title="项目总结--公司公用">
            <ProjectSummary :project="ProjectSummary_dialog.project">

            </ProjectSummary>
        </el-dialog>

        <el-dialog :visible.sync="ProjectDailyManage_dialog.show" width="90%" top="10px"
            :title="ProjectDailyManage_dialog.title">
            <ProjectDailyManage :project="ProjectDailyManage_dialog.project">
            </ProjectDailyManage>
        </el-dialog>

        <el-dialog :visible.sync="ProjectPrepare_dialog.show" width="90%" top="10px" :modal="false"
            :title="ProjectPrepare_dialog.title">
            <ProjectPrepare :project-data="ProjectPrepare_dialog.project" :all-project="AllProject"></ProjectPrepare>
        </el-dialog>

        <el-dialog :visible.sync="ProjectReport_dialog.show" width="95%" top="10px" :modal="false"
            :title="ProjectReport_dialog.title">
            <ProjectReport :project="ProjectReport_dialog.project"></ProjectReport>
        </el-dialog>

        <el-dialog v-if="ProjectFile_dialog.show" :visible.sync="ProjectFile_dialog.show" width="100%" :modal="false"
            :title="ProjectFile_dialog.title" :fullscreen="true">
            <ProjectFile :projectlist="ProjectFile_dialog.project" />
        </el-dialog>
		
		<el-dialog v-if="Personnel_Entry.show" :visible.sync="Personnel_Entry.show" width="100%"  :modal="false"
			:title="Personnel_Entry.title" :fullscreen="true">
			<PersonnelEntry @updataList="formdata" :project="Personnel_Entry.project"></PersonnelEntry>
		</el-dialog>
		
		<el-dialog v-if="Payroll_Entry.show" :visible.sync="Payroll_Entry.show" width="100%"  :modal="false"
			:title="Payroll_Entry.title" :fullscreen="true">
			<payrollList @updataList="formdata" :project="Payroll_Entry.project"></payrollList>
		</el-dialog>

		<el-dialog v-if="PayrollReality_Entry.show" :visible.sync="PayrollReality_Entry.show" width="100%"  :modal="false"
			:title="PayrollReality_Entry.title" :fullscreen="true">
			<payrollRealityList @updataList="formdata" :project="PayrollReality_Entry.project"></payrollRealityList>
		</el-dialog>
		
		<el-dialog v-if="Apply_Entry.show" :visible.sync="Apply_Entry.show" width="100%" :modal="false" 
			:title="Apply_Entry.title" :fullscreen="true">
			<ApplyIndex @updataList="formdata" :project="Apply_Entry.project"></ApplyIndex>
		</el-dialog>
		
		<el-dialog v-if="PayrollFormNew_Entry.show" :visible.sync="PayrollFormNew_Entry.show" width="100%"  :modal="false" :title="PayrollFormNew_Entry.title" :fullscreen="true">
			<Living></Living>
		</el-dialog>

    </div>
</template>

<script>
import * as publicjs from "../../../public/Scriput/Public";
import ProjectFiling from "./ProjectFiling";
import Approval from "./Approval";
import ProjectFinance from "./ProjectFinance";
import ProjectSummary from "./ProjectSummary";
import ProjectDailyManage from "./ProjectDailyManage";
import ProjectPrepare from "./ProjectPrepare";
import ProjectReport from "./ProjectReport";
import ProjectFile from "./ProjectFile"
import PersonnelEntry from "./PersonnelEntry.vue"
import payrollList from "./Payroll/payrollList"
import payrollRealityList from "./PayrollReality/payrollRealityList.vue"
import ApplyIndex from "./Apply/Index.vue"
import Living from "./Living/Index.vue"
import dayjs from 'dayjs'

export default {
    name: "ProjectManagement",
    components: {
        ProjectFiling, Approval,
        ProjectFinance, ProjectSummary,
        ProjectDailyManage, ProjectPrepare,
        ProjectReport, ProjectFile,PersonnelEntry,payrollList,
		payrollRealityList,ApplyIndex,Living
    },
    data() {
        return { 
            add:true,
            UpProject:{},
            ProjectDe: false,
            ProjectSummary_dialog: {
                show: false,
                project: {},
            },
            ProjectFinance_dialog: {
                show: false,
                project: {},
            },
            ProjectDailyManage_dialog: {
                show: false,
                project: {},
                title: '',
            },
            ProjectPrepare_dialog: {
                show: false,
                project: {},
                title: '',
            },
            ProjectReport_dialog: {
                show: false,
                project: {},
                title: '',
            },
            // 项目文件
            ProjectFile_dialog: {
                show: false,
                project: {},
                title: ""
            },
			Personnel_Entry:{
				show: false,
				project: {},
				title: "人员录入"
			},
			Payroll_Entry:{
				show: false,
				project: {},
				title: "收方工资单"
			},
			PayrollReality_Entry:{
				show: false,
				project: {},
                ProjectName:'',
				title: "实际收方工资单"
			},
			Apply_Entry:{
				show: false,
				project: {},
				title: "报销单"
			},
			PayrollFormNew_Entry:{
				show: false,
				title: "生活费计划单"
			},
            AllDepartment: [],
            AllProject: [],
            //表格数据
            tableData: [],
            //分页数据绑定
            pagination: {
                currentPage: 1,
                pagesizes: [10, 20, 30, 40, 50],
                pagesize: 10,
                total: 0
            },
            //查询实体
            selectfrom: {
                project: {
                    ProjectType: 0,
                    Id: 0,
                    MemberId: '',
                    HeadUserId: '',
                    DepartmentId: 0,
                },
                NoApproval: false,
                StartDate: '',
                EndDate: '',
            },
            //多选列表的数据集合
            SelectMore_lis: [],
            Project_filing_dialog: false,
            Approval_dialog: {
                show: false,
                projectdata: {},
            },
            // 表格按钮是否显示
            buttonShow: false
        }
    },
    created() {
        this.AllProject = publicjs.GetAllProject(this.$http)
        this.AllDepartment = publicjs.GetAllDepartment(this.$http)
        this.formdata()
        this.IsAdmin()
    },
    methods: {
        IsAdmin() {
            const _this = this;
            console.log(this.$store.state.user.roleid);
            if (this.$store.state.user.roleid != 1) {
                _this.ProjectDe = false;
            } else {
                _this.ProjectDe = true;
            }
        },
        //表格单个删除
        BatchDeleteOne_event(obj) {
            this.SelectMore_lis = [];
            this.SelectMore_lis.push(obj)
            this.BatchDelete_event()
        },
		//人员选择
		PersonnelEntry_event(obj){
			this.Personnel_Entry.show = true
			this.Personnel_Entry.project = obj	
            this.Personnel_Entry.title="人员录入--"+obj.ProjectName
		},
		//收方工资单
		RetrievPayRoll_event(obj){
            console.log(121);
			this.Payroll_Entry.show = true
			this.Payroll_Entry.project = obj	
            this.Payroll_Entry.title="收方工资单--"+obj.ProjectName
		},
		//实发工资单
		RetrievPayRollReality_event(obj){
			this.PayrollReality_Entry.show = true
			this.PayrollReality_Entry.project = obj	
		},
		RetrievApply_event(obj){
			this.Apply_Entry.show = true
			this.Apply_Entry.project = obj	
            this.Apply_Entry.title="报销单--"+obj.ProjectName
		},
        //数据加载
        formdata() {
            this.$http.post("Project1/GetProjectDetail", {
				StartDate: this.selectfrom.StartDate,
				EndDate: this.selectfrom.EndDate,
                Project: this.selectfrom.project,
                currentPage: this.pagination.currentPage,
                pagesize: this.pagination.pagesize,
                NoApproval: this.selectfrom.NoApproval,
            }).then(res => {
                this.tableData = res.data.data.map(x=>{
					return {
						...x,
						HeadUserId: Number(x.HeadUserId)
					}
				})
                this.pagination.total = res.data.count
            })
        },
        //批量删除
        BatchDelete_event() {
            let idlis = []
            let delect_bool = true
            if (this.SelectMore_lis.length == 0) {
                this.$message.warning('您还未选择需要删除的设备!')
            } else {
                for (let i = 0; i < this.SelectMore_lis.length; i++) {
                    idlis.push(this.SelectMore_lis[i].Id)
                    if (this.SelectMore_lis[i].Amount > this.SelectMore_lis[i].StockAmount) {
                        this.$message.warning(this.SelectMore_lis[i].DeviceName + '存在未归还的物资，不能直接删除!')
                        delect_bool = false
                        break;
                    }
                }
                if (delect_bool) {
                    this.$confirm('你确定要删除吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'error'
                    }).then(() => {
                        let loadding = this.openLoading();
                        this.$http.post('Project1/DeleteProjectContent', idlis).then(res => {
                            loadding.close();
                            if (res.data.mes.IsSuccess) {
                                this.$message.success(res.data.mes.Msg)
                                this.formdata()
                                this.SelectMore_lis = []
                            } else {
                                this.$message.warning(res.data.mes.Msg)
                            }
                        }).catch(() => {
                            loadding.close();
                            this.$message.error('服务器异常,请联系管理员!')
                        })
                    }).catch(() => {
                        this.$message.info('已取消!')
                        this.SelectMore_lis = []
                    })
                }
            }
        },
        //表格数据选择事件
        SelectionChange_event(value) {
            this.SelectMore_lis = value
        },
        //表格数据序列号
        indexMethod(index) {
            return ((this.pagination.currentPage - 1) * this.pagination.pagesize) + index + 1
        },
        //获取对应人员名字
        GetUserName(value) {
            let name = ''
            if (value != 0) {
                for (let i = 0; i < this.$store.state.AllUsers.length; i++) {
                    if (this.$store.state.AllUsers[i].Id == value) {
                        name = this.$store.state.AllUsers[i].UserName
                        return name
                    }
                }
            }
        },
        //获取对应部门名字
        GetDepartmentName(value) {
            let name = ''
            if (value != 0) {
                for (let i = 0; i < this.AllDepartment.length; i++) {
                    if (this.AllDepartment[i].Id == value) {
                        name = this.AllDepartment[i].DepartmentName
                        return name
                    }
                }
            }
        },
        //表格数据合集
			getSummaries(param) {
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '总价';
						return;
					}
					const values = data.map(item => Number(item[column.property]));
					if(index == 6||index == 8){
						if (!values.every(value => isNaN(value))) {
							sums[index] = values.reduce((prev, curr) => {
								const value = Number(curr);
								if (!isNaN(value)) {
									let sum =  parseFloat(prev)  + parseFloat(curr)
									return sum.toFixed(2);
								} else {
									return prev.toFixed(2);
								}
							}, 0);
							sums[index] += index!=7?' 元':'';
						} else {
							sums[index] = '';
						}						
					}
				});
				return sums;
			},
        //时间转化
        frtDate(val) {
            return publicjs.formatDateTime(val)
        },
        //时间转化2
        frtDateTwo(val) {
            if (val != null) {
                let time = val.split(" ")[0]
                if (time == '0001-01-01') {
                    return ''
                } else {
                    return time
                }
            } else {
                return ""
            }
        },
        // 表格工具栏是否显示知识库
        doFileRightView(row) {
            if (!row.FileRightView) {
                if (this.$store.state.user.id === 1) {
                    return true;
                } else {
                    return false;
                }
            }
            let fileRightView = row.FileRightView.split(',');
            if (fileRightView.indexOf(this.$store.state.user.id + "") >= 0 || row.HeadUserId === this.$store.state.user.id + "" || this.$store.state.user.id === 1) {
                return true
            } else {
                return false
            }
        },
        //表格工具栏按钮
        TableProjectEvent(obj, type) {
            let _this = this
            switch (type) {
                case "Material":
                    break;
                case "Approval": 
                console.log(obj);
                _this.UpProject=obj;
                _this.add=false;
				_this.Project_filing_dialog = true;
                // _this.Approval_dialog.show = true
                    // obj.CreateDate = obj.CreateDate ? new Date(obj.CreateDate) : new Date();
                    // obj.FinishDate = obj.FinishDate ? obj.FinishDate : new Date((new Date(obj.CreateDate)).getTime() + (1000 * 60 * 60 * 24 * 30));
                    // _this.Approval_dialog.projectdata = obj
                    break;
                case "Prepare":
                    _this.ProjectPrepare_dialog.show = true
                    _this.ProjectPrepare_dialog.project = obj
                    _this.ProjectPrepare_dialog.title = "项目前期准备阶段--" + obj.ProjectName
                    break;
                case "Daily"://项目日常
                    _this.ProjectDailyManage_dialog.show = true;
                    _this.ProjectDailyManage_dialog.project = obj;
                    _this.ProjectDailyManage_dialog.title = "项目日常管理阶段--" + obj.ProjectName;
                    break;
                case "Summary":
                    _this.ProjectSummary_dialog.show = true;
                    _this.ProjectSummary_dialog.project = obj;
                    break;
                case "Finance":
                    _this.ProjectFinance_dialog.show = true;
                    _this.ProjectFinance_dialog.project = obj;
                    break;
                case "Report":
                    _this.ProjectReport_dialog.show = true;
                    _this.ProjectReport_dialog.project = obj;
                    _this.ProjectReport_dialog.title = "项目报表--" + obj.ProjectName;
                    break;
                // 项目文件
                case "File":
                    _this.ProjectFile_dialog.show = true;
                    _this.ProjectFile_dialog.title = "知识库--" + obj.ProjectName;
                    _this.ProjectFile_dialog.project = obj;
                    break;
            }
        },
		//新建项目
		createNewProjectEvent(){
			this.Project_filing_dialog = true; 
			this.add = true; 
			this.UpProject = {					
				HeadUserId: "",
				ProjectNumber: '',
				ProjectName: '',
				PartA: '',
				EstimatedContractAmount: 0,
				CollectionAmount: '0',
				Remark: '',
				StartDate: '',
				EndDate: '',
				Managementfee: 0,
				Id: 0,
				SettleMoney:0,
				ContractamountInside:0,
				ContractamountExternal :0,
				Managementproportion :0,
			}
		},
		//项目完结
		projectOver_Event(row){
			this.$http.post('Project1/SetProjectEndById',{
				ProjectId:row.Id
			}).then(res=>{
				const {
					StatusCode,
					Data,
					Message
				} = res.data || 0
				if(StatusCode == 200){
					this.$message.success('修改成功')
					this.formdata()
				}else{
					this.$message.warning(Message)
				}
			})
		},
		//时间转化
		shijianzhuanhua(time){
			if(time=='') return ''
			else return dayjs(time).format('YYYY-MM-DD')
		},
    }
}
</script>

<style scoped>

</style>
